package com.d2.pay.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Auth: Alexander Lo
 * Date: 2020-03-24
 * Description:
 */
@Component
@Slf4j
public class NettySession {

    static private Map<String, Channel> sessions = new ConcurrentHashMap<>();

    public static Channel getSession(String token){
        return sessions.get(token);
    }


    public static void removeSession(String token){
        sessions.remove(token);
    }

    public static void  addSession(String token,Channel nettyClient){
        sessions.put(token, nettyClient);
    }




    public void sendMsg(String token,String msg){
        if (sessions.containsKey(token))
            sessions.get(token).writeAndFlush(msg);

    }

    public void sendMsg(String token, byte[] msg){
        if (sessions.containsKey(token)){
            log.info(Arrays.toString(msg));
            sessions.get(token).writeAndFlush(Unpooled.copiedBuffer(msg));
        }


    }


}
